package com.vehiclesecure.service;

import com.vehiclesecure.model.MaintenanceRecord;
import com.vehiclesecure.model.User;
import com.vehiclesecure.model.Vehicle;
import com.vehiclesecure.repository.MaintenanceRecordRepository;
import com.vehiclesecure.repository.UserRepository;
import com.vehiclesecure.repository.VehicleRepository;
import com.vehiclesecure.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
// import java.util.Optional;

@Service
public class MaintenanceRecordService {

    @Autowired
    private MaintenanceRecordRepository maintenanceRecordRepository;

    @Autowired
    private VehicleRepository vehicleRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private VehicleService vehicleService;

    public MaintenanceRecord createMaintenanceRecord(MaintenanceRecord record, Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        Vehicle vehicle = vehicleRepository.findById(record.getVehicleId())
                .orElseThrow(() -> new RuntimeException("车辆不存在"));

        // 验证用户是否有权限访问该车辆
        if (!vehicleService.hasAccessToVehicle(user.getId(), record.getVehicleId())) {
            throw new RuntimeException("无权访问该车辆");
        }

        record.setVehiclePlate(vehicle.getLicensePlate());
        record.setReportedBy(user.getId());
        record.setReportedByName(user.getUsername());
        record.setReportedAt(LocalDateTime.now());
        record.setStatus(MaintenanceRecord.MaintenanceStatus.PENDING);

        return maintenanceRecordRepository.save(record);
    }

    public List<MaintenanceRecord> getMaintenanceRecordsByVehicle(String vehicleId, Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 验证用户是否有权限访问该车辆
        if (!vehicleService.hasAccessToVehicle(user.getId(), vehicleId)) {
            throw new RuntimeException("无权访问该车辆");
        }

        return maintenanceRecordRepository.findByVehicleIdOrderByReportedAtDesc(vehicleId);
    }

    public List<MaintenanceRecord> getMaintenanceRecordsForServiceProvider(Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (!"SERVICE_PROVIDER".equals(user.getRole())) {
            throw new RuntimeException("只有服务商可以查看维修记录");
        }

        return maintenanceRecordRepository.findByServiceProviderIdOrderByReportedAtDesc(user.getId());
    }

    public List<MaintenanceRecord> getPendingMaintenanceRecordsForServiceProvider(Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (!"SERVICE_PROVIDER".equals(user.getRole())) {
            throw new RuntimeException("只有服务商可以查看维修记录");
        }

        return maintenanceRecordRepository.findByServiceProviderIdAndStatusOrderByReportedAtDesc(
                user.getId(), MaintenanceRecord.MaintenanceStatus.PENDING);
    }

    public MaintenanceRecord assignToServiceProvider(String recordId, String serviceProviderId, Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 只有管理员可以分配
        if (!"ADMIN".equals(user.getRole())) {
            throw new RuntimeException("只有管理员可以分配维修记录");
        }

        MaintenanceRecord record = maintenanceRecordRepository.findById(recordId)
                .orElseThrow(() -> new RuntimeException("维修记录不存在"));

        User serviceProvider = userRepository.findById(serviceProviderId)
                .orElseThrow(() -> new RuntimeException("服务商不存在"));

        if (!"SERVICE_PROVIDER".equals(serviceProvider.getRole())) {
            throw new RuntimeException("指定的用户不是服务商");
        }

        record.setServiceProviderId(serviceProviderId);
        record.setServiceProviderName(serviceProvider.getUsername());
        record.setAssignedAt(LocalDateTime.now());
        record.setStatus(MaintenanceRecord.MaintenanceStatus.ASSIGNED);

        return maintenanceRecordRepository.save(record);
    }

    public MaintenanceRecord updateMaintenanceStatus(String recordId, MaintenanceRecord.MaintenanceStatus status, String notes, Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        MaintenanceRecord record = maintenanceRecordRepository.findById(recordId)
                .orElseThrow(() -> new RuntimeException("维修记录不存在"));

        // 验证权限
        if (!"SERVICE_PROVIDER".equals(user.getRole()) || 
            !user.getId().equals(record.getServiceProviderId())) {
            throw new RuntimeException("无权更新该维修记录");
        }

        record.setStatus(status);
        record.setNotes(notes);
        
        if (status == MaintenanceRecord.MaintenanceStatus.COMPLETED) {
            record.setCompletedAt(LocalDateTime.now());
        }

        return maintenanceRecordRepository.save(record);
    }

    public MaintenanceRecord getMaintenanceRecord(String recordId, Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        MaintenanceRecord record = maintenanceRecordRepository.findById(recordId)
                .orElseThrow(() -> new RuntimeException("维修记录不存在"));

        // 验证权限
        boolean hasAccess = user.getRole().equals("ADMIN") ||
                           user.getRole().equals("SERVICE_PROVIDER") && user.getId().equals(record.getServiceProviderId()) ||
                           vehicleService.hasAccessToVehicle(user.getId(), record.getVehicleId());

        if (!hasAccess) {
            throw new RuntimeException("无权查看该维修记录");
        }

        return record;
    }

    public List<MaintenanceRecord> getMyReportedRecords(Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        return maintenanceRecordRepository.findByReportedByOrderByReportedAtDesc(user.getId());
    }

    public long getPendingCountForServiceProvider(Authentication authentication) {
        String userEmail = authentication.getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (!"SERVICE_PROVIDER".equals(user.getRole())) {
            return 0;
        }

        return maintenanceRecordRepository.countByServiceProviderIdAndStatus(
                user.getId(), MaintenanceRecord.MaintenanceStatus.PENDING);
    }
}